package com.heima.MyflectDemo1;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

public class Demo2 {
    public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException, NoSuchFieldException {
        //创建class对象
        Class clazz = Class.forName("com.heima.MyflectDemo1.Student");
        //创建constroter对象并且创建一个学生类对象并准备赋值
        Constructor constructor = clazz.getConstructor();
        Student student = (Student) constructor.newInstance();
        //获取成员变量的对象
        Field name = clazz.getDeclaredField("name");
        // setAccessible(true)方法取消权限检查---暴力反射（不推荐使用，破坏了开发中的封装的原则）
        name.setAccessible(true);
        //赋值
        name.set(student,"李四");
        Field age = clazz.getDeclaredField("age");
        age.setAccessible(true);
        age.set(student,28);
        System.out.println(student);

    }
}
